package com.sjy.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import com.sjy.qqfile.QQfilter.QQAuthenticationFilter;
import com.sjy.qqfile.QQfilter.QQAuthenticationManager;
import com.sjy.security.MyFilterSecurityInterceptor;
import com.sjy.security.MyPasswordEncoder;
import com.sjy.security.UserDetailsServiceImpl;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

	@Autowired
	MyFilterSecurityInterceptor MyFilterSecurityInterceptor;

	@Bean
	UserDetailsService customUserService() {
		return new UserDetailsServiceImpl();
	}

	@Bean
	@Override
	protected AuthenticationManager authenticationManager() throws Exception {
		return super.authenticationManager();
	}

	@Override
	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
		auth.userDetailsService(customUserService()).passwordEncoder(new MyPasswordEncoder());
		/*
		 * auth .inMemoryAuthentication()
		 * .withUser("user").password("password").roles("USER").authorities("SYS_User");
		 */
		// auth.inMemoryAuthentication().passwordEncoder(new
		// BCryptPasswordEncoder()).withUser("1").password(new
		// BCryptPasswordEncoder().encode("1")).roles("USER","ADMIN").au;

	}

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		/*http.addFilterBefore(new com.sjy.security.KaptchaAuthenticationFilter("/login1", "/login1?error"),
				UsernamePasswordAuthenticationFilter.class);*/
		// 在 UsernamePasswordAuthenticationFilter 前添加 QQAuthenticationFilter
        http.addFilterAt(qqAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
		http.authorizeRequests().antMatchers("/getKaptchaImage").permitAll() // 没有登陆可以访问 放一些公共的接口
																									// 比如登陆 注册 等等接口
				.anyRequest() // 其他所有请求登陆之后可以访问 //必须验证
				.authenticated()
				/**
				 * /////缺点 当有一个（URL）接口 没有存储数据库的的时候 当登陆之后 也是可以请求这个URL的
				 */
				.and().formLogin().loginPage("/login1")
				// 设置默认登录成功跳转页面
				.defaultSuccessUrl("/main", true).failureUrl("/login1?error").permitAll().and().logout()
				// 默认注销行为为logout，可以通过下面的方式来修改
				.logoutUrl("/custom-logout")
				// 设置注销成功后跳转页面，默认是跳转到登录页面
				.logoutSuccessUrl("/login1").permitAll().and().exceptionHandling().accessDeniedPage("/myerror");// 无权访问;
		// http.addFilterBefore(MyFilterSecurityInterceptor,
		// FilterSecurityInterceptor.class);

	}

	@Override
	public void configure(WebSecurity web) throws Exception {
		// 解决静态资源被拦截的问题
		web.ignoring().antMatchers("/", "/*.html", "/favicon.ico", "/**/*.html", "/**/*.css");
	}

	/**
     * 自定义 QQ登录 过滤器
     */
    private QQAuthenticationFilter qqAuthenticationFilter(){
        QQAuthenticationFilter authenticationFilter = new QQAuthenticationFilter("/login/qq");
        SimpleUrlAuthenticationSuccessHandler successHandler = new SimpleUrlAuthenticationSuccessHandler();
        successHandler.setAlwaysUseDefaultTargetUrl(true);
        successHandler.setDefaultTargetUrl("/qq");
        authenticationFilter.setAuthenticationManager(new QQAuthenticationManager());
        authenticationFilter.setAuthenticationSuccessHandler(successHandler);
        return authenticationFilter;
    }
}
